import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useFavoritesStore = defineStore('favorites', () => {
  // 收藏列表
  const favoritesList = ref([])
  
  // 收藏数量
  const favoritesCount = computed(() => favoritesList.value.length)
  
  // 检查商品是否已收藏
  const isFavorited = (productId) => {
    return favoritesList.value.some(item => item.id === productId)
  }
  
  // 添加收藏
  const addToFavorites = (product) => {
    if (!isFavorited(product.id)) {
      const favoriteItem = {
        ...product,
        favoriteTime: new Date().toISOString()
      }
      favoritesList.value.push(favoriteItem)
      saveToLocalStorage()
      return true
    }
    return false
  }
  
  // 取消收藏
  const removeFromFavorites = (productId) => {
    const index = favoritesList.value.findIndex(item => item.id === productId)
    if (index > -1) {
      favoritesList.value.splice(index, 1)
      saveToLocalStorage()
      return true
    }
    return false
  }
  
  // 批量取消收藏
  const removeMultipleFavorites = (productIds) => {
    let removedCount = 0
    productIds.forEach(id => {
      if (removeFromFavorites(id)) {
        removedCount++
      }
    })
    return removedCount
  }
  
  // 清空收藏
  const clearAllFavorites = () => {
    favoritesList.value = []
    saveToLocalStorage()
  }
  
  // 获取收藏商品
  const getFavoriteById = (productId) => {
    return favoritesList.value.find(item => item.id === productId)
  }
  
  // 搜索收藏商品
  const searchFavorites = (keyword) => {
    if (!keyword) return favoritesList.value
    return favoritesList.value.filter(item => 
      item.name.toLowerCase().includes(keyword.toLowerCase()) ||
      item.category.toLowerCase().includes(keyword.toLowerCase())
    )
  }
  
  // 按时间排序
  const sortByTime = (ascending = false) => {
    favoritesList.value.sort((a, b) => {
      const timeA = new Date(a.favoriteTime).getTime()
      const timeB = new Date(b.favoriteTime).getTime()
      return ascending ? timeA - timeB : timeB - timeA
    })
  }
  
  // 按价格排序
  const sortByPrice = (ascending = false) => {
    favoritesList.value.sort((a, b) => {
      const priceA = parseFloat(a.currentPrice) || 0
      const priceB = parseFloat(b.currentPrice) || 0
      return ascending ? priceA - priceB : priceB - priceA
    })
  }
  
  // 保存到本地存储
  const saveToLocalStorage = () => {
    try {
      localStorage.setItem('enba-favorites', JSON.stringify(favoritesList.value))
    } catch (error) {
      console.error('保存收藏数据失败:', error)
    }
  }
  
  // 从本地存储加载
  const loadFromLocalStorage = () => {
    try {
      const stored = localStorage.getItem('enba-favorites')
      if (stored) {
        favoritesList.value = JSON.parse(stored)
      }
    } catch (error) {
      console.error('加载收藏数据失败:', error)
      favoritesList.value = []
    }
  }
  
  // 初始化默认收藏数据
  const initDefaultFavorites = () => {
    if (favoritesList.value.length === 0) {
      const defaultFavorites = [
        {
          id: 'f001',
          name: '经典款运动鞋',
          category: '运动鞋',
          currentPrice: '299',
          originalPrice: '399',
          image: 'https://picsum.photos/200/200?random=1',
          favoriteTime: new Date(Date.now() - 86400000).toISOString() // 1天前
        },
        {
          id: 'f002',
          name: '时尚休闲包',
          category: '箱包',
          currentPrice: '199',
          originalPrice: '299',
          image: 'https://picsum.photos/200/200?random=2',
          favoriteTime: new Date(Date.now() - 172800000).toISOString() // 2天前
        },
        {
          id: 'f003',
          name: '智能手表',
          category: '数码',
          currentPrice: '899',
          originalPrice: '1299',
          image: 'https://picsum.photos/200/200?random=3',
          favoriteTime: new Date(Date.now() - 259200000).toISOString() // 3天前
        }
      ]
      favoritesList.value = defaultFavorites
      saveToLocalStorage()
    }
  }
  
  return {
    favoritesList,
    favoritesCount,
    isFavorited,
    addToFavorites,
    removeFromFavorites,
    removeMultipleFavorites,
    clearAllFavorites,
    getFavoriteById,
    searchFavorites,
    sortByTime,
    sortByPrice,
    saveToLocalStorage,
    loadFromLocalStorage,
    initDefaultFavorites
  }
})
